package com.kingdee.pda.ui.fast_allot;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.basecommon.http.rxjava.BaseResponse;
import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.R;
import com.kingdee.pda.adapter.FastAllotGoodsListAdapter;
import com.kingdee.pda.callback.OnCheckBoxChangeListener;
import com.kingdee.pda.callback.OnEditTextChangeListener;
import com.kingdee.pda.commonmethod.CheckSkuPresenter;
import com.kingdee.pda.commonmethod.CheckSkuView;
import com.kingdee.pda.commonmethod.QueryStockPresenter;
import com.kingdee.pda.commonmethod.QueryStockView;
import com.kingdee.pda.entity.FastAllotRequestBean;
import com.kingdee.pda.entity.Goods;
import com.kingdee.pda.entity.LocationListBean;
import com.kingdee.pda.entity.QtfInOutEntryInfoRequest;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.entity.WarehouseAreaLocationInfo;
import com.kingdee.pda.entity.WarehouseLocation;
import com.kingdee.pda.ui.activity.BaseTitleActivity;
import com.kingdee.pda.ui.activity.MoveInWarehouseActivity;
import com.kingdee.pda.ui.popupwindow.ListSelectorPpWindow;
import com.kingdee.pda.util.CommonUtil;
import com.kingdee.pda.util.WarehouseUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;


/**
 * 快速调拨操作
 * Created by dlj
 * DATE 2021/8/31
 * TIME 13:25
 */
public class FastAllotOperateActivity extends BaseTitleActivity implements View.OnKeyListener, View.OnClickListener,
        OnCheckBoxChangeListener, OnEditTextChangeListener, FastAllotContract.IFastAllotView, QueryStockView, CheckSkuView {
    private WarehouseLocation mMoveOutLocation;//移出库位信息
    private WarehouseLocation mMoveInLocation;//移入库位信息
    private Goods mOperateGoods;//商品操作对象
    private int mCanMoveQty = 1;//可移动数量
    private EditText et_outLocationcode;
    private EditText et_skuCode;
    private EditText et_inLocationcode;
    private EditText et_number, et_invStatusName;
    private TextView tv_warehouseInformation, tv_maxNumber, tv_total;
    private TextView tv_edit, tv_delete, tv_save;
    private Button btn_last, btn_finish;
    private RecyclerView recyclerView;
    private Warehouse outOwner;//移出货主货主信息
    private Warehouse inWarehouse;//移入仓库信息
    private int scanStyle;//扫描方式
    private FastAllotGoodsListAdapter adapter;
    private List<QtfInOutEntryInfoRequest> goodsInfoList = new ArrayList();//商品明细
    private FastAllotPresenter fastAllotPresenter;
    private boolean isMoveOut;
    private CheckSkuPresenter checkSkuPresenter;
    private QueryStockPresenter queryStockPresenter;
    private List<LocationListBean> locationListBeanList = new ArrayList<>();

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, FastAllotOperateActivity.class));
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        super.onActivityCreate(savedInstanceState);
        setContentView(R.layout.activity_fast_allot_operate);
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("快速调拨");

        et_outLocationcode = findViewById(R.id.et_outLocationcode);
        et_skuCode = findViewById(R.id.et_skuCode);
        et_inLocationcode = findViewById(R.id.et_inLocationcode);
        et_number = findViewById(R.id.et_number);
        et_invStatusName = findViewById(R.id.et_invStatusName);

        setEditTextScannerEvents(et_outLocationcode, this);
        setEditTextScannerEvents(et_skuCode, this);
        setEditTextScannerEvents(et_inLocationcode, this);
        setEditTextScannerEvents(et_number, this);

        tv_warehouseInformation = findViewById(R.id.tv_warehouseInformation);
        tv_maxNumber = findViewById(R.id.tv_maxNumber);
        tv_total = findViewById(R.id.tv_total);
        tv_edit = findViewById(R.id.tv_edit);
        tv_delete = findViewById(R.id.tv_delete);
        tv_save = findViewById(R.id.tv_save);

        btn_last = findViewById(R.id.btn_last);
        btn_finish = findViewById(R.id.btn_finish);

        tv_edit.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        btn_last.setOnClickListener(this);
        btn_finish.setOnClickListener(this);
        findViewById(R.id.iv_select_invStatusName).setOnClickListener(this);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new FastAllotGoodsListAdapter(this, goodsInfoList, this, this);
        recyclerView.setAdapter(adapter);

        addMoveCountEditChangeListener();

        fastAllotPresenter = new FastAllotPresenter(this, this);
        checkSkuPresenter = new CheckSkuPresenter(this, this);
        queryStockPresenter = new QueryStockPresenter(this, this);
    }

    @Override
    protected void initData() {
        super.initData();

        outOwner = (Warehouse) getIntent().getSerializableExtra("outOwner");
        inWarehouse = (Warehouse) getIntent().getSerializableExtra("inWarehouse");
        scanStyle = getIntent().getIntExtra("scanStyle", 0);
        if (scanStyle == 1) {//如果是逐件扫描模式，数量输入框不可输入
            et_number.setText("1");
            et_number.setEnabled(false);
        } else {
            et_number.setEnabled(true);
        }

        tv_warehouseInformation.setText(WarehouseUtil.getCurrentWarehouse().getName() + "->" + inWarehouse.getName());

        //点击上一页，回来应保存已扫数据
        List<QtfInOutEntryInfoRequest> goodList = (List<QtfInOutEntryInfoRequest>) getIntent().getSerializableExtra("goodList");
        if (goodList != null && goodList.size() > 0) {
            goodsInfoList.clear();
            goodsInfoList.addAll(goodList);
            adapter.notifyDataSetChanged();
            reflushTvTotol();
            btn_finish.setEnabled(true);
        }

        //查询移入仓库的默认移入库位
        HashMap<String, Object> map = new HashMap<>();
        map.put("warehouseId", inWarehouse.getId());
        fastAllotPresenter.getDefaultLocationcode(map);
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (!(v instanceof EditText)) {
            return false;
        }
        EditText editText = (EditText) v;
        String input = editText.getText().toString().trim();
        if (TextUtils.isEmpty(input)) return false;
        if ((keyCode == KeyEvent.KEYCODE_SYSRQ || keyCode == KeyEvent.KEYCODE_ENTER) && event.getAction() == KeyEvent.ACTION_UP) {
            switch (v.getId()) {
                case R.id.et_outLocationcode:
                    queryLocationInfo(input, true);
                    break;
                case R.id.et_skuCode:
                    if (mMoveOutLocation == null) {
                        SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "请输入调出库位", false, false);
                    } else {
                        String skuSplit = CommonUtil.skuCodeSplit(FastAllotOperateActivity.this, input);
                        if (TextUtils.isEmpty(skuSplit)) {
                            SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "商品条码截取结果为空，请检查输入和截图规则", false, false);
                            return false;
                        }
                        et_skuCode.setText(skuSplit);
                        queryGoodsInfo(skuSplit);
                    }
                    break;
                case R.id.et_inLocationcode:
                    queryLocationInfo(input, false);
                    break;
                case R.id.et_number:
                    try {
                        if (Integer.parseInt(input) > mCanMoveQty) {
                            et_number.setText(String.valueOf(mCanMoveQty));
                            et_number.setSelection(et_number.getText().length());
                        } else if (checkDataValid()) {
                            reflushListView(Integer.parseInt(input));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "数量输入有误！", false, false);
                    }
                    break;
            }
            return true;
        }
        return false;
    }

    /**
     * 查询库位信息
     *
     * @param locationNum 库位编码
     * @param isMoveOut   是否为移出仓库
     */
    private void queryLocationInfo(String locationNum, final boolean isMoveOut) {
        this.isMoveOut = isMoveOut;
        queryStockPresenter.queryWarehouseLocation(isMoveOut ? getCurrentWarehouse().getId() : inWarehouse.getId(), locationNum);
    }

    //查询库位库存信息
    private void queryGoodsLocationStock(final WarehouseLocation location) {
        if (mOperateGoods == null) {
            SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "请扫描或输入商品条码并按enter", false, false);
            CommonUtil.requestFocusAndNoClearText(et_skuCode);
            return;
        }
        queryStockPresenter.queryGoodsLocationStock(location, mOperateGoods.getSkuId(), location.getLocationId() == 0 ? 1 : 0);
    }

    /**
     * 刷新下方列表
     *
     * @param qty
     */
    private void reflushListView(int qty) {
        boolean isExit = false;
        for (QtfInOutEntryInfoRequest bean : goodsInfoList) {
            if (bean.getInlocationid() == mMoveInLocation.getLocationId() && bean.getOutlocationid() == mMoveOutLocation.getLocationId()
                    && bean.getInoutskuid() == mOperateGoods.getSkuId() && bean.getInvStatusId() == mMoveOutLocation.getSelectedStatusBean().getInvStatusId()) {
                bean.setInouttransferqty(bean.getInouttransferqty() + qty);
                isExit = true;
            }
        }

        if (!isExit) {
            QtfInOutEntryInfoRequest addBean = new QtfInOutEntryInfoRequest(mOperateGoods.getSkuId(), outOwner.getId(),
                    outOwner.getId(), mMoveOutLocation.getLocationId(), mMoveInLocation.getLocationId(), qty);
            addBean.setInoutskucode(mOperateGoods.getSkuCode());
            addBean.setInoutskubarcode(mOperateGoods.getItemBarcode());
            addBean.setSpecName(mOperateGoods.getSpecName());
            addBean.setInlocationcode(mMoveInLocation.getLocationCode());
            addBean.setOutlocationcode(mMoveOutLocation.getLocationCode());
            addBean.setInvStatusId(mMoveOutLocation.getSelectedStatusBean().getInvStatusId());
            addBean.setInvStatusName(mMoveOutLocation.getSelectedStatusBean().getInvStatusName());

            goodsInfoList.add(0, addBean);
        }

        btn_finish.setEnabled(true);
        adapter.notifyDataSetChanged();
        et_skuCode.setText("");
        if (scanStyle == 0) {
            et_number.setText("");
            CommonUtil.requestFocusAndClearText(et_outLocationcode);
        } else {
            CommonUtil.requestFocusAndClearText(et_skuCode);
        }

        reflushTvTotol();
    }

    //查询商品信息
    private void queryGoodsInfo(String barcode) {
        checkSkuPresenter.queryGoods(getCurrentWarehouse().getId(), mMoveOutLocation.getLocationId(), barcode);
    }

    private void addMoveCountEditChangeListener() {
        et_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int input = CommonUtil.formatStringToInt(et_number.getText().toString().trim());
                if (input > mCanMoveQty) {
                    et_number.setText(String.valueOf(mCanMoveQty));
                    et_number.setSelection(et_number.getText().length());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_edit:
                tv_edit.setVisibility(View.GONE);
                tv_delete.setVisibility(View.VISIBLE);
                tv_save.setVisibility(View.VISIBLE);
                adapter.setShowCheckbox(true);
                break;
            case R.id.tv_delete:
                Iterator<QtfInOutEntryInfoRequest> iterator = goodsInfoList.iterator();
                while (iterator.hasNext()) {
                    QtfInOutEntryInfoRequest next = iterator.next();
                    if (next.isChecked()) {
                        iterator.remove();
                    }
                }
                adapter.notifyDataSetChanged();

                reflushTvTotol();
                break;
            case R.id.tv_save:
                tv_edit.setVisibility(View.VISIBLE);
                tv_delete.setVisibility(View.GONE);
                tv_save.setVisibility(View.GONE);
                adapter.setShowCheckbox(false);
                break;
            case R.id.btn_last:
                Intent intent = new Intent();
                intent.putExtra("goodList", (Serializable) goodsInfoList);
                setResult(2000, intent);
                finish();
                break;
            case R.id.btn_finish:
                if (goodsInfoList != null && goodsInfoList.size() > 0) {
                    FastAllotRequestBean fastAllotRequestBean = new FastAllotRequestBean(outOwner.getId(), outOwner.getId(), WarehouseUtil.getCurrentWarehouse().getId(), inWarehouse.getId());
                    fastAllotRequestBean.setQtfInOutEntryInfoList(goodsInfoList);
                    fastAllotRequestBean.setType("1");
                    fastAllotPresenter.fastallotOrderCommit(fastAllotRequestBean);
                }
                break;
            case R.id.iv_select_invStatusName:
                showInvStatusNameSelector();
                break;
        }
    }

    /**
     * 展示库存状态选择框
     */
    private void showInvStatusNameSelector() {
        ListSelectorPpWindow<LocationListBean> locationSelector = new ListSelectorPpWindow<>(this,
                R.drawable.shape_bg_edit_selected,
                et_invStatusName.getWidth(),
                locationListBeanList,
                new ListSelectorPpWindow.onItemSelectedListener() {
                    @Override
                    public void onItemSelected(Object item) {
                        LocationListBean locationListBean = ((LocationListBean) item);
                        mMoveOutLocation.setSelectedStatusBean(locationListBean);
                        et_invStatusName.setText(locationListBean.getInvStatusName());
                        calculateCanMoveQty();
                        CommonUtil.requestFocusAndNoClearText(et_number);
                    }
                });
        locationSelector.showAsDropDown(et_invStatusName, 0, 10);
    }

    /**
     * 刷新统计
     */
    private void reflushTvTotol() {
        Set<String> goodType = new HashSet<>();//记录商品种类
        int allQty = 0;//记录调拨总数量
        for (QtfInOutEntryInfoRequest bean : goodsInfoList) {
            goodType.add(bean.getInoutskuid() + "");
            allQty += bean.getInouttransferqty();
        }
        tv_total.setText("商品种类数：" + goodType.size() + "   调拨总数：" + allQty);
    }

    @Override
    public void changeWarehouse(Warehouse warehouse) {
        mMoveOutLocation = null;
        clearAllView();
    }

    private void calculateCanMoveQty() {
        if (mMoveOutLocation == null || mMoveInLocation == null) {
            return;
        }
        //可移入量 = 库位的库容 - 库位库存数 - 该库位待移入数量
        int canMoveInQty = mMoveInLocation.getCanMoveInQty();
        if (canMoveInQty <= 0) {
            tv_maxNumber.setText("* 移入库位没有可用库容量！");
        } else {
            //可移出数量
            int canMoveOutQty = mMoveOutLocation.getCanMoveOutQty();
            mCanMoveQty = canMoveInQty > canMoveOutQty ? canMoveOutQty : canMoveInQty;
            if (mCanMoveQty == Integer.MAX_VALUE) {
                tv_maxNumber.setText("* 最大可调拨量：无限制");
            } else {
                tv_maxNumber.setText("* 最大可调拨量：" + mCanMoveQty);
            }
        }
    }

    private boolean checkDataValid() {
        if (getCurrentWarehouse() == null) {
            SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "仓库信息获取失败", false, false);
            return false;
        }
        if (mMoveOutLocation == null) {
            SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "调出库位信息获取失败", false, false);
            return false;
        }
        if (mOperateGoods == null) {
            SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "商品信息获取失败", false, false);
            return false;
        }
        if (mMoveInLocation == null) {
            SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "调入库位信息获取失败", false, false);
            return false;
        }
//        if ((mMoveInLocation.getLocationId() + "").equals(mMoveOutLocation.getLocationId() + "") || et_inLocationcode.getText().toString().equals(et_outLocationcode.getText().toString())) {
//            SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "调出和调入库位不能一样", false, false);
//            return false;
//        }
        if (mCanMoveQty == 0) {
            SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "商品可移库数量为0", false, false);
            return false;
        }
        int moveQty = CommonUtil.formatStringToInt(et_number.getText().toString().trim());
        if (moveQty == 0) {
            SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "请输入移库数量", false, false);
            return false;
        }
        return true;
    }

    private void clearAllView() {

        mOperateGoods = null;
        mCanMoveQty = 0;
        et_skuCode.setText("");
        tv_maxNumber.setText("");
        tv_total.setText("商品种类数：0   调拨总数：0");
        goodsInfoList.clear();
        adapter.notifyDataSetChanged();

        if (scanStyle == 0)
            et_number.setText("");

        btn_finish.setEnabled(false);
        CommonUtil.requestFocusAndClearText(et_outLocationcode);
    }

    @Override
    public void onCheckChanged(int position, boolean isChecked) {
        goodsInfoList.get(position).setChecked(isChecked);
        boolean hasChecked = false;
        a:
        for (QtfInOutEntryInfoRequest bean : goodsInfoList) {
            if (bean.isChecked()) {
                hasChecked = true;
                break a;
            }
        }

        if (hasChecked) {
            tv_delete.setTextColor(getResources().getColor(R.color.color_4f7eff));
        } else {
            tv_delete.setTextColor(getResources().getColor(R.color.color_999999));
        }
    }

    @Override
    public void onEditTextChanged(int position, int num) {
        goodsInfoList.get(position).setInouttransferqty(num);

        reflushTvTotol();
    }

    @Override
    public void fastallotOrderCommitSuccess(BaseResponse result) {
        SpeakUtils.speakWithToast(FastAllotOperateActivity.this, "调拨成功！", false, true);
        clearAllView();
    }

    @Override
    public void fastallotOrderCommitFailed(String msg) {
        SpeakUtils.speakWithToast(FastAllotOperateActivity.this, msg, false, false);
    }

    @Override
    public void getDefaultLocationcodeSuccess(WarehouseAreaLocationInfo locationInfos) {
        for (WarehouseAreaLocationInfo.AreaInfo areaInfo : locationInfos.getAreaList()) {
            if (areaInfo.getAreaType() == 1 && areaInfo.getDefaultArea()) {//收货区并且是默认收货区
                for (WarehouseAreaLocationInfo.AreaInfo.LocationInfo locationInfo : areaInfo.getLocationList()) {
                    if (locationInfo.getDefaultLocation()) {
                        et_inLocationcode.setText(locationInfo.getLocationCode());
                    }
                }
            }
        }
    }

    @Override
    public void queryWarehouseLocationSuccess(WarehouseLocation warehouseLocation) {
        if (isMoveOut) {
            mMoveOutLocation = warehouseLocation;
            et_skuCode.requestFocus();
        } else {
            mMoveInLocation = warehouseLocation;
            mMoveInLocation.setWarehouseId(inWarehouse.getId());
            queryGoodsLocationStock(mMoveInLocation);
        }
    }

    @Override
    public void queryWarehouseLocationFailed(String message) {
        SpeakUtils.speakWithToast(FastAllotOperateActivity.this, message, false, false);
        if (isMoveOut) {
            mMoveOutLocation = null;
            CommonUtil.requestFocusAndClearText(et_outLocationcode);
        } else {
            mMoveInLocation = null;
            CommonUtil.requestFocusAndClearText(et_inLocationcode);
        }
    }

    @Override
    public void queryGoodsSuccess(Goods goods) {
        mOperateGoods = goods;
        if (isMoveOut) {
            queryGoodsLocationStock(mMoveOutLocation);
        } else {
            if (!TextUtils.isEmpty(et_inLocationcode.getText().toString())) {
                queryLocationInfo(et_inLocationcode.getText().toString(), false);
            } else {
                CommonUtil.requestFocusAndNoClearText(et_inLocationcode);
            }
        }
    }

    @Override
    public void queryGoodsFailed(String message) {
        SpeakUtils.speakWithToast(FastAllotOperateActivity.this, message, false, false);
        CommonUtil.requestFocusAndClearText(et_skuCode);
    }

    @Override
    public void queryGoodsLocationStockSuccess(WarehouseLocation warehouseLocation) {
        if (!isMoveOut) {
            mMoveInLocation = warehouseLocation;
            calculateCanMoveQty();
            //如果是逐件扫描，扫完移入库位就应该增加数量 1
            if (scanStyle == 1 && checkDataValid()) {
                reflushListView(1);
            } else {
                if (TextUtils.isEmpty(et_outLocationcode.getText().toString())) {
                    CommonUtil.requestFocusAndNoClearText(et_outLocationcode);
                } else {
                    CommonUtil.requestFocusAndNoClearText(et_number);
                }
            }
        } else {
            mMoveOutLocation = warehouseLocation;
            locationListBeanList.clear();
            locationListBeanList.addAll(mMoveOutLocation.getList());
            //默认选中第一个状态
            if (locationListBeanList.size() > 0) {
                mMoveOutLocation.setSelectedStatusBean(locationListBeanList.get(0));
                et_invStatusName.setText(mMoveOutLocation.getSelectedStatusBean().getInvStatusName());
            }

            if (!TextUtils.isEmpty(et_inLocationcode.getText().toString())) {
                queryLocationInfo(et_inLocationcode.getText().toString(), false);
            } else {
                CommonUtil.requestFocusAndNoClearText(et_inLocationcode);
            }
        }
    }

    @Override
    public void queryGoodsLocationStockFailed(String message) {
        SpeakUtils.speakWithToast(FastAllotOperateActivity.this, message, false, false);
    }
}
